package com.bwie.common.utils;

import com.alibaba.fastjson.JSON;
import com.bwie.common.constants.Constants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.exceptions.BusinessException;
import com.bwie.common.pojo.res.LoginRes;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;

public class TokenUtils {
    public static LoginRes getUser(HttpServletRequest request, RedisTemplate<String, Object> redisTemplate){
        String token = request.getHeader(TokenConstants.TOKEN);
        // 判空
        if (StringUtils.isBlank(token)){
            throw new BusinessException(TokenConstants.TOKEN_IS_NULL);
        }
        String userKey;
        try {
            // 判断token是否合法
            userKey = JwtUtils.getUserKey(token);
        } catch (Exception e) {
            throw new BusinessException(TokenConstants.TOKEN_WRONG);
        }
        String loginTokenKey = TokenConstants.LOGIN_TOKEN_KEY + userKey;
        // 判断token是否失效
        if (Boolean.FALSE.equals(redisTemplate.hasKey(loginTokenKey))){
            throw new BusinessException(TokenConstants.TOKEN_EXPIRE);
        }
        String userStr = (String) redisTemplate.opsForValue().get(loginTokenKey);
        return JSON.parseObject(userStr, LoginRes.class);
    }
}
